import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
from collections import Counter

raw_data_x = [[3.393533211, 2.331273381],  # y=0
              [3.110073483, 1.781539638],  # y=0
              [1.343808831, 3.368360954],  # y=0
              [3.582294042, 4.679179110],  # y=0
              [2.280362439, 2.866990263],  # y=0
              [7.423436942, 4.696522875],  # y=1
              [5.745051997, 3.533989803],  # y=1
              [9.172168622, 2.511101045],  # y=1
              [7.792783481, 3.424088941],  # y=1
              [7.939820817, 0.791637231]   # y=1
             ]
raw_data_y = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]


x_train = np.array(raw_data_x)
y_train = np.array(raw_data_y)


# y_train == 0 means take y axis values are 0, that's mean take five points
plt.scatter(x_train[y_train == 0, 0], x_train[y_train == 0, 1], color='black')
plt.scatter(x_train[y_train == 1, 0], x_train[y_train == 1, 1], color='red')


x_new_point = np.array([8.093607318, 3.365731514])
plt.scatter(x_new_point[0], x_new_point[1], color='blue')



# kNN 过程
# distances = []
# for x in x_train:
    # array 里的每个元素都会相减 , 并使用欧拉距离公式 算出 训练集中的数据与x点之间的距离
    # distance = sqrt(np.sum((x - x_new_point)**2))
    # distances.append(distance)


distances = [sqrt(np.sum((x - x_new_point)**2)) for x in x_train]
# [8 7 5 6 9 3 0 1 4 2] 拿到的结果集 返回的是对应的下标 下标表示的就是 距离x_new_point距离最近的点的元素排序表示
nearest = np.argsort(distances)

k = 6
# y轴表示一个分类，取出最近的6个点，并算出top k 中分类个数，供下一步使用
topK_y = [y_train[i] for i in nearest[:k]]

# Counter({1: 5, 0: 1}) 表示1有5个 0有1个
votes = Counter(topK_y)
predict_y = votes.most_common(1)[0][0]
# 这里最终结果取出来的是1 表示在kNN算法中，新添加的x元素，离red点更近
print(predict_y)
plt.show()